package com.brian.hystrix.demo;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;

/**
 * Created by Brian on 2018/4/25 15:21
 */
public class CommandHelloWorld extends HystrixCommand<String> {
    private final String name;

    public CommandHelloWorld(String name) {
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
        this.name = name;
    }

    @Override
    protected String run() {
        //关键点：把一个RPC调用，封装在一个HystrixCommand里面
        if(System.currentTimeMillis() > 0){
            throw new RuntimeException(); // 抛异常时会调用 getFallback 方法
        }
        return "Hello " + name + "!";
    }

    // 降级
    @Override
    protected String getFallback() {
        return "fallback: " + name;
    }

    public static void main(String[] args){
        /* 调用程序对CommandHelloWorld实例化，执行execute()即触发HelloWorldHystrixCommand.run()的执行 */
        String result = new CommandHelloWorld("HLX").execute();
        System.out.println(result);  // 打印出Hello HLX
    }
}
